const { Op, sequelize } = require('sequelize');
const { User, Order } = require('../models');

// 获取用户列表（管理员）
exports.getUsers = async (req, res, next) => {
    try {
        const {
            page = 1,
            limit = 20,
            search,
            role,
            isActive
        } = req.query;

        const offset = (page - 1) * limit;
        const whereClause = {};
        
        if (search) {
            whereClause[Op.or] = [
                { username: { [Op.like]: `%${search}%` } },
                { email: { [Op.like]: `%${search}%` } },
                { firstName: { [Op.like]: `%${search}%` } },
                { lastName: { [Op.like]: `%${search}%` } }
            ];
        }
        
        if (role) {
            whereClause.role = role;
        }
        
        if (isActive !== undefined) {
            whereClause.isActive = isActive === 'true';
        }

        const { count, rows: users } = await User.findAndCountAll({
            where: whereClause,
            attributes: { exclude: ['password'] },
            limit: parseInt(limit),
            offset: parseInt(offset),
            order: [['createdAt', 'DESC']]
        });

        res.json({
            success: true,
            data: {
                users,
                pagination: {
                    page: parseInt(page),
                    limit: parseInt(limit),
                    total: count,
                    pages: Math.ceil(count / limit)
                }
            }
        });
    } catch (error) {
        next(error);
    }
};

// 获取单个用户详情（管理员）
exports.getUserById = async (req, res, next) => {
    try {
        const { id } = req.params;

        const user = await User.findByPk(id, {
            attributes: { exclude: ['password'] },
            include: [
                {
                    model: Order,
                    as: 'orders',
                    attributes: ['id', 'orderNumber', 'status', 'totalAmount', 'createdAt'],
                    limit: 5,
                    order: [['createdAt', 'DESC']]
                }
            ]
        });

        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        // 获取用户统计信息
        const orderStats = await Order.findOne({
            where: { userId: id },
            attributes: [
                [sequelize.fn('COUNT', sequelize.col('id')), 'totalOrders'],
                [sequelize.fn('SUM', sequelize.col('totalAmount')), 'totalSpent']
            ],
            raw: true
        });

        res.json({
            success: true,
            data: {
                user,
                stats: {
                    totalOrders: orderStats.totalOrders || 0,
                    totalSpent: parseFloat(orderStats.totalSpent || 0).toFixed(2)
                }
            }
        });
    } catch (error) {
        next(error);
    }
};

// 更新用户状态（管理员）
exports.updateUserStatus = async (req, res, next) => {
    try {
        const { id } = req.params;
        const { isActive, role } = req.body;

        // 不能修改自己的状态
        if (parseInt(id) === req.user.id) {
            return res.status(400).json({
                success: false,
                message: '不能修改自己的状态'
            });
        }

        const user = await User.findByPk(id);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        const updateData = {};
        if (isActive !== undefined) updateData.isActive = isActive;
        if (role !== undefined) updateData.role = role;

        await user.update(updateData);

        res.json({
            success: true,
            message: '用户状态更新成功',
            data: { user }
        });
    } catch (error) {
        next(error);
    }
};

// 删除用户（管理员）
exports.deleteUser = async (req, res, next) => {
    try {
        const { id } = req.params;

        // 不能删除自己
        if (parseInt(id) === req.user.id) {
            return res.status(400).json({
                success: false,
                message: '不能删除自己的账户'
            });
        }

        const deletedRowsCount = await User.destroy({
            where: { id }
        });

        if (deletedRowsCount === 0) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        res.json({
            success: true,
            message: '用户删除成功'
        });
    } catch (error) {
        next(error);
    }
};